#!/bin/bash

OSNAME=Unknown

get_osname() {
	# depend installmethod
	method=$1
	# find OS name in /proc/cmdline
	
	c=$(cat /proc/cmdline); 
	on1=${c##*osname=};
	OSNAME=${on1%% *};
	
	if [ -z "$OSNAME" ]; then
		echo "osname is empty on /proc/cmdline, please check"
		exit 1
	fi

}

get_osname
for t in $(cat /proc/cmdline); do
    case $t in
        installmethod=net)
			mkdir /tos/img/
			echo "Downloading image"
			/tos/tlog -m "Downloading image"
			wget http://192.168.199.200:8444/img/${OSNAME} -O /tos/img/os.img
			if [ $? -eq 0 ]; then
				/tos/tlog -m "Image download finished"
			else
				/tos/tlog -m "Image download failed"
				exit 1
			fi
            break
            ;;
		installmethod=harddisk)
			mkdir /tos/img/
			grep -q "xvda" /proc/cmdline
			if [ $? -eq 0 ]; then
				mount /dev/sdb1 /tos/img/
				mv /tos/img/${OSNAME}.sqfs /tos/img/os.img
			else
				mount /dev/sda4 /data
				/tos/tlog -m "copy /data/${OSNAME}.sqfs to /tos/img/os.img"
				cp -v /data/${OSNAME}.sqfs /tos/img/os.img
				cp -v /data/hardinstall_extra.rpm /tos/img && /tos/tlog -m "copy hardinstall_extra.rpm to /tos/img/"
				cp -v /data/hardinstall_rc.local /tos/img && /tos/tlog -m "copy hardinstall_rc.local to /tos/img/"
				cp -v /data/hardinstall_script /tos/img && /tos/tlog -m "copy hardinstall_script to /tos/img/"
                cp -v /data/hardinstall_iface_hwaddr /tos/img && /tos/tlog -m "copy hardinstall_iface_hwaddr to /tos/img/"
				/tos/tlog -m  "umount /data"
				umount /data
			fi
			python /tos/hardinstall_check.py
			if [ $? -ne 0 ]; then
				/tos/tlog -m "hardinstall check failed"
				exit 1
		    fi
			break
		    ;;
        installmethod=cdrom)
			mkdir /tos/img/
            echo "mount /dev/cdrom to /data"
            sleep 10	
			mount /dev/cdrom /data
			echo "copy /data/${OSNAME}.sqfs to /tos/img/os.img"
			cp -v /data/${OSNAME}.sqfs /tos/img/os.img
			echo "umount /dev/cdrom"
			umount /data
            break;
            ;;
        installmethod=usb)
            echo "usb"
            break;
            ;;
    esac
done
exit 0
